package cn.kgc.javaweb.servlet;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @author: mosin
 * @version: v1.0  2022/3/18
 */
@WebServlet("/checkusername")
public class CheckUsernameServlet extends HttpServlet {
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //获取用户名
        req.setCharacterEncoding("utf-8");
        String username = req.getParameter("username");
        System.out.println("username = " + username);

        //程序阻塞 加大程序运行的时间
        try {
            Thread.sleep(5000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        resp.setContentType("application/json;charset=utf-8");
        //获取输出流
        PrintWriter writer = resp.getWriter();

        // TODO 调用service  处理相关业务
        String str = null;
        if ("admin".equals(username)){ // 用户已被占用
            //将响应的信息 利用json格式进行响应
            /*
            * js对象  {name:'lisi',age:20}
            * json {"name":"lisi","age":20}
            *
            * code: 状态码
            * msg: 提示信息
            * data: 响应的数据
            * */
           str = "{\"code\":1,\"msg\":\"用户名不可用\"}";
            //通过响应对象 将json字符串类型的数据进行响应
        }else{
           str = "{\"code\":0,\"msg\":\"用户名可用\"}";
        }
        //通过响应对象 将json字符串类型的数据进行响应
        writer.write(str);
        writer.close();
    }
}
